package com.zwy.ubts.utils;

import com.yg.yws.beans.RetType;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author Zhou Wenying
 * @Description:
 * @Date Created in 21:59 2023/3/7
 */
public class ImgUtil {

    public static byte[] upImage(HttpServletRequest req){
        //创建工厂实现类
        FileItemFactory fileItemFactory=new DiskFileItemFactory();
        ServletFileUpload servletFileUpload =new ServletFileUpload(fileItemFactory);

        byte[] bytes = new byte[0];
        try {
            //解析上传的信息
            List<FileItem> list = servletFileUpload.parseRequest(req);
            //遍历上传的信息--解析表单内的内容
            for (FileItem fileItem : list) {
                if (!fileItem.isFormField())  {   //文件信息
                    System.out.println("文件 表单属性" + fileItem.getFieldName());
                    System.out.println("上传的文件名:" + fileItem.getName());
                    bytes = fileItem.get();
                }else {
                    System.out.println(fileItem.getFieldName()+":"+fileItem.getString());
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }


    public RetType downImage(String imgName, HttpServletResponse resp) throws Exception {

        byte [] img = new byte[0];
        String filename = null;
        //读数据库
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(img);
        ServletOutputStream outputStream = resp.getOutputStream();
        //实现浏览器下下载功能
        IOUtils.copy(stream, outputStream);
        return RetType.retEmpty();
    }
}
